import pandas

import logging as log

from common.conf import Conf


def read_cases(xlsfile, columns=None):
    try:
        data = pandas.read_excel('../excelcase/'+xlsfile, usecols=columns)
        data['参数'] = data['参数'].apply(eval)
        data['预期结果'] = data['预期结果'].apply(eval)
        case_info = data['用例编号'] + ':' + data['用例说明']
        url = Conf().host + data['接口路径']
        data.insert(0, '用例信息', case_info)
        data.insert(1, '接口地址', url)
        data.drop(['用例编号', '用例说明', '接口路径'], axis=1, inplace=True)
        cases = data.values.tolist()
        log.info(f'读取用例文件{xlsfile}成功')
        return cases
    except BaseException as e:
        log.error(f'读取用例出错==错误类型：{type(e).__name__}==错误内容：{e}')
        exit()



def send_request(url, method, request_type, args):  # url是接口地址，method是请求方法，request_type是请求类型，args是请求参数，
    try:
        send = f"requests.{method}('{url}',{request_type}={args})"  # 返回值是响应类型（在响应头中）、响应正文
        res = eval(send)
        if 'json' in res.headers['content-type']:
            res_type = 'json'
            actual = res.json()
        elif 'text' in res.headersp['content-type']:
            res_type = 'text'
            actual = res.text
        else:  # 暂不处理其他类型
            pass
        log.info(f"执行requests.{method}('{url},{request_type}={args}成功')")
        return res_type, actual
    except BaseException as e:
        log.error(f'发送请求出错==错误类型：{type(e).__name__}==错误内容：{e}')
        exit()


def check(case_info, res_type, actual, expect):
    try:
        passed = False  # 测试是否通过,假设测试失败
        if res_type == 'text' and expect in actual:
            passed = True
        elif res_type == 'json' and expect == actual:
            passed = True
        else:  # 其他情况暂时跳过
            pass
        if passed:
            log.info(f'{case_info}==响应结果比对通过')
            msg=''
        else:
            msg=f'{case_info}==响应结果比对失败==预期：{expect}==实际：{actual}'
            log.warning(msg)
        return passed,msg
    except BaseException as e:
        log.error(f'响应结果比对出错==错误类型：{type(e).__name__}==错误内容：{e}')
        exit()


if __name__=='__main__':
     print(read_cases('login.xlsx',['用例编号', '用例说明', '接口路径','请求方法','请求类型', '参数', '预期结果']))
     print(send_request('http://192.168.196.128/apitest/login/', 'post', 'data',
                        {'username': 'test01', 'password': '123456'}))
     print(send_request('http://192.168.196.128/apitest/signup/', 'post', 'json',
                        {'username': 'test01', 'password': '123456', 'confirm': '123456', 'name': '测试一'}))
     check('用例信息', 'json', {'a': 1, 'b': 2}, {'a': 1, 'b': 2})
     check('用例信息', 'json', {'a': 1, 'b': 2}, {'a': 1, 'b': 3})